<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="$router.go(-1)"></i>
      <span>商家列表</span>
    </header>

    <!-- 排序选项 -->
    <div class="sort-bar">
      <div 
        class="sort-item" 
        :class="{ active: currentSort === 'rating' }"
        @click="sortBy('rating')"
      >
        <span>综合排序</span>
        <i class="fa fa-caret-down"></i>
      </div>
      <div 
        class="sort-item" 
        :class="{ active: currentSort === 'distance' }"
        @click="sortBy('distance')"
      >
        <span>距离最近</span>
        <i class="fa fa-caret-down"></i>
      </div>
      <div 
        class="sort-item" 
        :class="{ active: currentSort === 'sales' }"
        @click="sortBy('sales')"
      >
        <span>销量最高</span>
        <i class="fa fa-caret-down"></i>
      </div>
    </div>

    <!-- 商家列表 -->
    <div class="business-list" v-if="businessList.length > 0">
      <div 
        class="business-item" 
        v-for="business in businessList" 
        :key="business.businessId"
        @click="goToBusinessInfo(business.businessId)"
      >
        <img :src="getBusinessImage(business.businessId)" alt="商家图片" @error="handleImageError($event, business.businessId)">
        <div class="business-info">
          <div class="business-info-header">
            <h3>{{ business.businessName }}</h3>
            <div class="business-rating">
              <i class="fa fa-star"></i>
              <span>{{ business.rating || 4.0 }}</span>
            </div>
          </div>
          <p class="business-explain">{{ business.businessExplain }}</p>
          <div class="business-stats">
            <span class="distance">
              <i class="fa fa-map-marker"></i>
              {{ business.distance }}km
            </span>
            <span class="sales">月售{{ business.monthlySales }}单</span>
            <span class="delivery">
              <i class="fa fa-motorcycle"></i>
              配送费¥{{ business.deliveryPrice }}
            </span>
          </div>
          <div class="price-info">
            <span>起送¥{{ business.starPrice }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载中状态 -->
    <div v-else-if="loading" class="loading">
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty">
      <p>暂无商家信息</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'

// 导入商家图片
import sj01 from '@/assets/sj01.png'
import sj02 from '@/assets/sj02.png'
import sj03 from '@/assets/sj03.png'
import sj04 from '@/assets/sj04.png'
import sj05 from '@/assets/sj05.png'
import sj06 from '@/assets/sj06.png'
import sj07 from '@/assets/sj07.png'
import sj08 from '@/assets/sj08.png'
import sj09 from '@/assets/sj09.png'

const axios = inject('axios')
const router = useRouter()

// 响应式数据
const businessList = ref([])
const currentSort = ref('rating') // 默认综合排序
const loading = ref(true)

// 排序方法
const sortBy = async (sortType) => {
  console.log('=== 开始排序 ===')
  console.log('排序类型:', sortType)
  
  if (currentSort.value === sortType) {
    console.log('相同排序类型，跳过')
    return
  }
  
  currentSort.value = sortType
  loading.value = true
  
  try {
    // 使用统一的API调用方式
    const response = await axios.post(`/api/BusinessController/listBusinessBySort`, {
      sortType: sortType
    })
    console.log('排序请求成功:', response)
    
    if (response && Array.isArray(response)) {
      businessList.value = response
      console.log('更新商家列表，共', response.length, '个商家')
      
      // 打印前3个商家的排序信息
      response.slice(0, 3).forEach((business, index) => {
        console.log(`商家${index + 1}: ${business.businessName} - 距离:${business.distance}km 销量:${business.monthlySales} 评分:${business.rating}`)
      })
    } else {
      console.warn('返回数据格式错误:', response)
      businessList.value = []
    }
  } catch (error) {
    console.error('排序请求失败:', error)
    console.log('尝试使用GET方法请求')
    
    // 备用方案：使用GET请求
    try {
      const getResponse = await axios.get(`/api/BusinessController/listBusinessBySort?sortType=${sortType}`)
      console.log('GET请求成功:', getResponse)
      
      if (getResponse && Array.isArray(getResponse)) {
        businessList.value = getResponse
        console.log('使用GET方法成功获取数据，共', getResponse.length, '个商家')
      } else {
        throw new Error('GET请求也失败了')
      }
    } catch (getError) {
      console.error('GET请求也失败:', getError)
    // 使用模拟数据作为降级方案
    businessList.value = getMockData(sortType)
      console.log('使用模拟数据，共', businessList.value.length, '个商家')
    }
  } finally {
    loading.value = false
  }
}

// 跳转到商家详情页
const goToBusinessInfo = (businessId) => {
  console.log('跳转到商家详情:', businessId)
  router.push({
    path: '/businessInfo',
    query: { businessId }
  })
}

// 获取商家图片
const getBusinessImage = (businessId) => {
  // 优先使用后端图片API获取商家上传的图片
  // 使用商家图片二进制数据API端点
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080';
  // 添加时间戳参数，避免浏览器缓存
  const timestamp = new Date().getTime();
  const backendImageUrl = `${apiBaseUrl}/api/images/business-binary/${businessId}?t=${timestamp}`;
  
  // 返回后端URL，并通过onerror处理图片加载失败的情况
  return backendImageUrl;
}

// 处理图片加载失败，使用预存的静态图片
const handleImageError = (event, businessId) => {
  console.warn(`商家图片加载失败，使用默认图片: businessId=${businessId}`);
  // 使用导入的商家图片作为降级方案
  const imageMap = {
    1: sj01, 2: sj02, 3: sj03, 4: sj04, 5: sj05,
    6: sj06, 7: sj07, 8: sj08, 9: sj09,
    10001: sj01, 10002: sj02, 10003: sj03, 10004: sj04,
    10005: sj05, 10006: sj06, 10007: sj07, 10008: sj08, 10009: sj09
  }
  event.target.src = imageMap[businessId] || sj01;
}

// 模拟数据（降级方案）
const getMockData = (sortType) => {
  const mockData = [
    {
      businessId: 10001,
      businessName: '万家饺子（软件园18店）',
      businessExplain: '各种饺子',
      starPrice: 18.00,
      deliveryPrice: 3.50,
      distance: 1.2,
      monthlySales: 156,
      rating: 4.5
    },
    {
      businessId: 10002,
      businessName: '小锅豆豆腐馆（全运店）',
      businessExplain: '小锅套餐',
      starPrice: 15.00,
      deliveryPrice: 3.00,
      distance: 2.3,
      monthlySales: 89,
      rating: 4.3
    },
    {
      businessId: 10003,
      businessName: '麦当劳麦乐送（全运路店）',
      businessExplain: '汉堡薯条',
      starPrice: 25.00,
      deliveryPrice: 4.00,
      distance: 1.8,
      monthlySales: 234,
      rating: 4.6
    }
  ]
  
  // 根据排序类型排序
  switch (sortType) {
    case 'distance':
      return mockData.sort((a, b) => a.distance - b.distance)
    case 'sales':
      return mockData.sort((a, b) => b.monthlySales - a.monthlySales)
    case 'rating':
      return mockData.sort((a, b) => b.rating - a.rating)
    default:
      return mockData
  }
}

// 初始化数据
const initData = async () => {
  console.log('=== 初始化商家列表 ===')
  await sortBy('rating') // 默认按评分排序
}

// 页面挂载时初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  overflow-y: auto;
}

/* header样式 */
header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.5vw;
  
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  
  display: flex;
  justify-content: center;
  align-items: center;
}

header i {
  font-size: 6vw;
  position: absolute;
  left: 4vw;
  cursor: pointer;
}

/* 排序栏样式 */
.sort-bar {
  width: 100%;
  height: 10vw;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  margin-top: 12vw;
  
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.sort-item {
  flex: 1;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 3.5vw;
  color: #666;
  transition: all 0.3s ease;
}

.sort-item.active {
  color: #0097ff;
  font-weight: bold;
}

.sort-item span {
  margin-right: 1vw;
}

.sort-item:hover {
  background-color: #f0f0f0;
}

/* 商家列表样式 */
.business-list {
  width: 100%;
  background-color: #fff;
  margin-top: 1vw;
}

.business-item {
  width: 100%;
  padding: 3vw;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
  
  display: flex;
  align-items: flex-start;
}

.business-item:hover {
  background-color: #f9f9f9;
}

.business-item img {
  width: 18vw;
  height: 18vw;
  border-radius: 2vw;
  margin-right: 3vw;
  flex-shrink: 0;
}

.business-info {
  flex: 1;
  width: 0;
}

.business-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2vw;
}

.business-info-header h3 {
  font-size: 4vw;
  color: #333;
  margin: 0;
  flex: 1;
}

.business-rating {
  display: flex;
  align-items: center;
  font-size: 3vw;
  color: #fec80e;
}

.business-rating i {
  margin-right: 1vw;
}

.business-rating span {
  color: #333;
  font-weight: bold;
}

.business-explain {
  font-size: 3vw;
  color: #999;
  margin: 0 0 2vw 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.business-stats {
  display: flex;
  align-items: center;
  font-size: 2.8vw;
  color: #666;
  margin-bottom: 2vw;
}

.business-stats span {
  margin-right: 3vw;
  display: flex;
  align-items: center;
}

.business-stats i {
  margin-right: 1vw;
  color: #999;
}

.distance {
  color: #0097ff !important;
}

.price-info {
  font-size: 2.8vw;
  color: #666;
}

/* 加载和空状态样式 */
.loading, .empty {
  width: 100%;
  height: 20vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 3.5vw;
  color: #999;
  background-color: #fff;
}

/* 响应式适配 */
@media (max-width: 480px) {
  header {
    height: 50px;
  }
  
  .sort-bar {
    height: 40px;
    margin-top: 50px;
  }
  
  .sort-item {
    font-size: 14px;
  }
  
  .business-item {
    padding: 12px;
  }
  
  .business-item img {
    width: 60px;
    height: 60px;
    margin-right: 12px;
  }
  
  .business-info-header h3 {
    font-size: 16px;
  }
  
  .business-explain {
    font-size: 12px;
  }
  
  .business-stats {
    font-size: 11px;
  }
}
</style>